package com.sinosoft.brokerchannel.base.server;

import com.sinosoft.brokerchannel.base.bins.InterfaceConfige;
import com.sinosoft.brokerchannel.base.bins.InterfaceTemplate;
import com.sinosoft.brokerchannel.base.bins.Template;
import com.sinosoft.brokerchannel.base.common.SystemParamFinal;
import com.sinosoft.brokerchannel.base.dao.InterfaceConfigeMapper;
import com.sinosoft.brokerchannel.base.dao.InterfaceTemplateMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 接口配置类
 */
@Service
public class InterfaceConfigeService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private InterfaceConfigeMapper interfaceConfigeMapper;
    @Autowired
    private InterfaceTemplateMapper interfaceTemplateMapper;

    /**
     * 获取模板
     *
     * @param channelCode
     * @param methodName
     * @return
     */
    @Cacheable("getTemplate")
    public List<Template> getTemplate(String channelCode, String methodName) {
        List<Template> templates = null;
        try {
            InterfaceConfige confige = interfaceConfigeMapper.selectByPrimaryKey(channelCode);
            if (confige == null) {
                confige = interfaceConfigeMapper.selectByPrimaryKey("default");
            }
            if (confige != null) {
                List<InterfaceTemplate> interfaceTemplates = interfaceTemplateMapper.getTemplates(confige.getTemplateversion(), methodName);
                if (interfaceTemplates != null && !interfaceTemplates.isEmpty()) {
                    templates = new ArrayList<>();
                    Template template;
                    Class c;
                    String[] include = null, filter = null;
                    for (InterfaceTemplate interfaceTemplate : interfaceTemplates) {
                        c = Class.forName("com.anxin.car.vo." + interfaceTemplate.getClassname());
                        if (interfaceTemplate.getIncludes() != null && !"".equals(interfaceTemplate.getIncludes())) {
                            include = interfaceTemplate.getIncludes().split(",");
                        }
                        if (interfaceTemplate.getFilters() != null && !"".equals(interfaceTemplate.getFilters())) {
                            filter = interfaceTemplate.getFilters().split(",");
                        }
                        template = new Template(c, include, filter);
                        templates.add(template);
                    }
                }
            }
        } catch (Exception e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
        }
        return templates;
    }
}
